// import userStorage from "../../utils/userStorage"; // 暂未使用
import Vue from 'vue';

const state = {
  // 语音连接状态
  voiceConnections: new Map(), // playerId -> RTCPeerConnection
  
  // 聊天室状态
  chatRooms: {
    public: {
      active: false,
      participants: [],
      muted: false
    },
    private: new Map() // "player1-player2" -> { active, participants, muted }
  },
  
  // 权限设置
  permissions: {
    publicChatEnabled: true,
    privateChatEnabled: true,
    storytellerChatEnabled: true,
    globalMute: false
  },
  
  // 玩家权限
  playerPermissions: {}, // playerId -> { canPublicChat, canPrivateChat, isMuted }
  
  // 私聊申请
  privateChatRequests: [], // [{ fromId, toId, timestamp, status }]
  
  // 音频流
  localStream: null,
  remoteStreams: new Map(), // playerId -> MediaStream
  
  // 测试模式
  testMode: process.env.NODE_ENV === 'development',
  simulatedConnections: new Map(), // 开发测试用
  
  // 连接状态
  connectionStates: new Map(), // playerId -> { status, quality, ping }
  
  // 说书人控制面板状态
  storytellerPanel: {
    visible: false,
    selectedPlayers: [],
    monitoringMode: false
  },

  // 服务器同步的显示名映射（playerId -> displayName）
  displayNames: new Map(),

  // 服务器同步的角色映射（playerId -> 'storyteller' | 'player' | 'guest'）
  roles: new Map(),

  // 完整的用户管理数据
  users: new Map(), // playerId -> User对象
  storytellerId: null,
  channelInfo: null,

  // 完整的房间管理数据
  rooms: new Map(), // roomId -> Room对象
  publicRoomId: null,
  roomStats: null,

  // UI 短暂提示（用counter触发响应式）
  uiBannerText: '',
  uiBannerCounter: 0,
  
  // 中心模态：收到的邀请信息 { roomId, ownerId, ownerName }
  incomingInvite: null,
  
  // 中心模态：房主待审批的加入请求 { roomId, requesterId, requesterName }
  joinApproval: null
};

const getters = {
  // 获取当前用户角色
  currentUserRole: (state, getters, rootState) => {
    // 统一用 session.isSpectator 判定：true = 说书人，false = 玩家
    return rootState.session.isSpectator === true ? 'storyteller' : 'player';
  },
  
  // 获取当前用户权限
  currentUserPermissions: (state, getters, rootState) => {
    const playerId = rootState.session.playerId;
    return state.playerPermissions[playerId] || {
      canPublicChat: true,
      canPrivateChat: true,
      isMuted: false
    };
  },
  
  // 获取活跃的聊天室
  activeChatRooms: (state) => {
    const active = [];
    
    // 公共聊天
    if (state.chatRooms.public.active) {
      active.push({
        type: 'public',
        participants: state.chatRooms.public.participants,
        muted: state.chatRooms.public.muted
      });
    }
    
    // 私人聊天
    state.chatRooms.private.forEach((room, roomId) => {
      if (room.active) {
        active.push({
          type: 'private',
          roomId,
          participants: room.participants,
          muted: room.muted
        });
      }
    });
    
    return active;
  },
  
  // 获取待处理的私聊申请
  pendingPrivateChatRequests: (state) => {
    return state.privateChatRequests.filter(req => req.status === 'pending');
  },
  
  // 获取连接质量统计
  connectionQualityStats: (state) => {
    const stats = {
      total: state.connectionStates.size,
      excellent: 0,
      good: 0,
      poor: 0,
      failed: 0
    };
    
    state.connectionStates.forEach(connection => {
      switch (connection.status) {
        case 'excellent': stats.excellent++; break;
        case 'good': stats.good++; break;
        case 'poor': stats.poor++; break;
        default: stats.failed++;
      }
    });
    
    return stats;
  }
};

const mutations = {
  // 设置本地音频流
  setLocalStream(state, stream) {
    state.localStream = stream;
  },
  
  // 添加远程音频流
  addRemoteStream(state, { playerId, stream }) {
    state.remoteStreams.set(playerId, stream);
  },
  
  // 移除远程音频流
  removeRemoteStream(state, playerId) {
    state.remoteStreams.delete(playerId);
  },
  
  // 更新聊天室状态
  updateChatRoom(state, { type, roomId, data }) {
    if (type === 'public') {
      state.chatRooms.public = { ...state.chatRooms.public, ...data };
    } else if (type === 'private') {
      const currentRoom = state.chatRooms.private.get(roomId) || {};
      const updatedRoom = { ...currentRoom, ...data };
      // 重要：克隆并替换 Map 引用以触发 Vue2 响应式
      const newPrivateMap = new Map(state.chatRooms.private);
      newPrivateMap.set(roomId, updatedRoom);
      state.chatRooms.private = newPrivateMap;
    }
  },
  
  // 更新玩家权限
  updatePlayerPermissions(state, { playerId, permissions }) {
    const merged = {
      ...(state.playerPermissions[playerId] || {}),
      ...permissions
    };
    Vue.set(state.playerPermissions, playerId, merged);
  },
  
  // 添加私聊申请
  addPrivateChatRequest(state, request) {
    state.privateChatRequests.push({
      ...request,
      id: Date.now(),
      timestamp: Date.now(),
      status: 'pending'
    });
  },
  
  // 更新私聊申请状态
  updatePrivateChatRequest(state, { requestId, status }) {
    const request = state.privateChatRequests.find(req => req.id === requestId);
    if (request) {
      request.status = status;
    }
  },
  
  // 设置全局权限
  setGlobalPermissions(state, permissions) {
    state.permissions = { ...state.permissions, ...permissions };
  },
  
  // 更新连接状态
  updateConnectionState(state, { playerId, connectionState }) {
    state.connectionStates.set(playerId, connectionState);
  },
  
  // 切换说书人面板
  toggleStorytellerPanel(state, visible) {
    state.storytellerPanel.visible = visible;
  },
  
  // 模拟连接（测试用）
  simulateConnection(state, { playerId, quality = 'excellent' }) {
    if (state.testMode) {
      state.simulatedConnections.set(playerId, {
        status: 'connected',
        quality,
        timestamp: Date.now()
      });
    }
  },

  // 设置玩家静音状态（本地立即生效）
  setPlayerMute(state, { playerId, muted }) {
    const merged = {
      ...(state.playerPermissions[playerId] || {}),
      isMuted: !!muted,
    };
    Vue.set(state.playerPermissions, playerId, merged);
  },

  // 触发居中提示
  showUiBanner(state, text) {
    state.uiBannerText = text || '';
    state.uiBannerCounter += 1;
  },

  // 设置/清除收到的邀请
  setIncomingInvite(state, invite) {
    state.incomingInvite = invite || null;
  },

  // 设置/清除房主审批请求
  setJoinApproval(state, approvalInfo) {
    state.joinApproval = approvalInfo || null;
  },

  // 设置（或覆盖）某个玩家在语音中的显示名称
  setDisplayName(state, { playerId, displayName }) {
    if (playerId) {
      state.displayNames.set(playerId, displayName || '');
    }
  },

  // 设置（或覆盖）某个玩家的角色
  setRole(state, { playerId, role }) {
    if (!playerId || !role) return;
    state.roles.set(playerId, role);
  },

  // 更新用户数据
  updateUser(state, user) {
    if (user && user.playerId) {
      state.users.set(user.playerId, user);
      // 同步到 roles 和 displayNames
      state.roles.set(user.playerId, user.role);
      state.displayNames.set(user.playerId, user.displayName);
    }
  },

  // 移除用户
  removeUser(state, playerId) {
    state.users.delete(playerId);
    state.roles.delete(playerId);
    state.displayNames.delete(playerId);
  },

  // 设置用户列表快照
  setUsersSnapshot(state, snapshot) {
    if (snapshot && snapshot.users) {
      // 清空现有数据
      state.users.clear();
      state.roles.clear();
      state.displayNames.clear();
      
      // 设置新数据
      Object.values(snapshot.users).forEach(user => {
        state.users.set(user.playerId, user);
        state.roles.set(user.playerId, user.role);
        state.displayNames.set(user.playerId, user.displayName);
      });
      
      state.storytellerId = snapshot.storytellerId;
      state.channelInfo = {
        channelId: snapshot.channelId,
        createdAt: snapshot.createdAt,
        onlineCount: snapshot.onlineCount,
        seatedCount: snapshot.seatedCount
      };
    }
  },

  // 更新房间数据
  updateRoom(state, room) {
    if (room && room.roomId) {
      state.rooms.set(room.roomId, room);
      if (room.type === 'public') {
        state.publicRoomId = room.roomId;
      }
    }
  },

  // 移除房间
  removeRoom(state, roomId) {
    state.rooms.delete(roomId);
    if (state.publicRoomId === roomId) {
      state.publicRoomId = null;
    }
  },

  // 设置房间列表快照
  setRoomsSnapshot(state, snapshot) {
    if (snapshot) {
      // 清空现有房间数据
      state.rooms.clear();
      state.publicRoomId = null;
      
      // 设置公聊房间
      if (snapshot.publicRoom) {
        state.rooms.set(snapshot.publicRoom.roomId, snapshot.publicRoom);
        state.publicRoomId = snapshot.publicRoom.roomId;
      }
      
      // 设置私聊房间
      if (snapshot.privateRooms && Array.isArray(snapshot.privateRooms)) {
        snapshot.privateRooms.forEach(room => {
          state.rooms.set(room.roomId, room);
        });
      }
      
      // 设置房间统计信息
      state.roomStats = {
        channelId: snapshot.channelId,
        createdAt: snapshot.createdAt,
        totalRooms: state.rooms.size,
        publicParticipants: snapshot.publicRoom ? snapshot.publicRoom.participantCount : 0,
        privateRooms: snapshot.privateRooms ? snapshot.privateRooms.length : 0
      };
    }
  }
};

const actions = {
  // 初始化语音聊天
  async initializeVoiceChat({ commit, dispatch }) {
    try {
      if (state.testMode) {
        // 开发模式：使用模拟音频
        const mockStream = await dispatch('createMockAudioStream');
        commit('setLocalStream', mockStream);
      } else {
        // 生产模式：获取真实麦克风
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true,
            sampleRate: 16000
          }
        });
        commit('setLocalStream', stream);
      }
      return true;
    } catch (error) {
      console.error('语音聊天初始化失败:', error);
      return false;
    }
  },
  
  // 创建模拟音频流（开发测试用）
  async createMockAudioStream() {
    const audioContext = new AudioContext();
    const oscillator = audioContext.createOscillator();
    const destination = audioContext.createMediaStreamDestination();
    
    oscillator.frequency.value = 440; // A4音符
    oscillator.connect(destination);
    oscillator.start();
    
    // 5秒后停止
    setTimeout(() => oscillator.stop(), 5000);
    
    return destination.stream;
  },
  
  // 申请私聊
  requestPrivateChat({ commit, rootState }, { targetPlayerId }) {
    const fromId = rootState.session.playerId;
    const request = {
      fromId,
      toId: targetPlayerId,
      type: 'private_chat_request'
    };
    
    commit('addPrivateChatRequest', request);
    
    // 发送到服务器
    rootState.socket.send('voice_chat_request', request);
  },
  
  // 处理私聊申请
  handlePrivateChatRequest({ commit, dispatch }, { requestId, approved }) {
    commit('updatePrivateChatRequest', { requestId, status: approved ? 'approved' : 'rejected' });
    
    if (approved) {
      dispatch('establishPrivateChat', { requestId });
    }
  },
  
  // 建立私人聊天
  async establishPrivateChat({ commit, state }, { requestId }) {
    const request = state.privateChatRequests.find(req => req.id === requestId);
    if (!request) return;
    
    const roomId = `${request.fromId}-${request.toId}`;
    
    commit('updateChatRoom', {
      type: 'private',
      roomId,
      data: {
        active: true,
        participants: [request.fromId, request.toId],
        muted: false
      }
    });
  },
  
  // 说书人控制：禁音玩家
  mutePlayer({ commit, rootState }, { playerId, muted = true }) {
    commit('updatePlayerPermissions', {
      playerId,
      permissions: { isMuted: muted }
    });
    
    // 发送到服务器
    rootState.socket.send('voice_chat_control', {
      type: 'mute_player',
      playerId,
      muted
    });
  },
  
  // 说书人控制：全局禁音
  setGlobalMute({ commit, rootState }, { muted = true }) {
    commit('setGlobalPermissions', { globalMute: muted });
    
    // 如果全局禁音，关闭所有聊天室
    if (muted) {
      commit('updateChatRoom', {
        type: 'public',
        data: { active: false }
      });
    }
    
    // 发送到服务器
    rootState.socket.send('voice_chat_control', {
      type: 'global_mute',
      muted
    });
  },
  
  // 监控连接质量
  monitorConnectionQuality({ commit }, { playerId }) {
    // 模拟连接质量检测
    const qualities = ['excellent', 'good', 'poor'];
    const randomQuality = qualities[Math.floor(Math.random() * qualities.length)];
    
    commit('updateConnectionState', {
      playerId,
      connectionState: {
        status: randomQuality,
        ping: Math.floor(Math.random() * 200) + 50,
        quality: randomQuality,
        timestamp: Date.now()
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};